<template>

  <!-- todo 根据条件从后端返回数据 -->
  <el-form ref="record_query_form" :label-position=" 'right' " label-width="80px"
           :inline="true" :model="record_fuzzy_search">

    <el-form-item label="小类">
      <FuzzySearchSmallVer2
          @DataUse="small_auto_complete_in_record($event as any)"
          ref="small_clear"
          :disable="false"
          @DataClear="small_auto_complete_in_record_clear()"
      />
    </el-form-item>

    <el-form-item label="处理方">
      <FuzzySearchHandleVer2
          @DataUse="handle_auto_complete_in_record($event as any)"
          @DataClear="handle_auto_complete_in_record_clear()"
          ref="handle_clear"
          :disable="false"
      />
    </el-form-item>

    <!-- 出库/入库/全部 -->
    <el-form-item label="出入库">
      <el-radio-group v-model="record_fuzzy_search.trend">
        <el-radio-button value="出库">出库</el-radio-button>
        <el-radio-button value="入库">入库</el-radio-button>
        <el-radio-button value="全部">全部</el-radio-button>
      </el-radio-group>
    </el-form-item>

    <el-form-item label="小数位数">
      <el-input-number v-model="record_fuzzy_search.scale" :step="1" :min="1" :max="4"/>
    </el-form-item>

    <!-- 日期范围 -->
    <el-form-item label="日期范围">
      <el-date-picker
          v-model="record_fuzzy_search.date_range"
          type="daterange"
          range-separator="To"
          start-placeholder="Start date"
          end-placeholder="End date"
          value-format="YYYY-MM-DD"
      />
    </el-form-item>


    <el-form-item>
      <el-button type="primary" @click="return_record_list()">搜索</el-button>
      <el-button @click=" table_head_select() ">选择显示的表头数据</el-button>
      <el-button @click=" return_inbound_list() ">根据所选生成单据</el-button>
    </el-form-item>

    <el-form-item label="搜索信息" >
      <el-descriptions border>
        <el-descriptions-item label="选定小类">{{ record_page_search_info.big_name_and_small_name }}</el-descriptions-item>
        <el-descriptions-item label="选定处理方">{{ record_page_search_info.handle_name }}</el-descriptions-item>
      </el-descriptions>
    </el-form-item>

  </el-form>
  <!-- todo 数据表显示区域 -->
  <el-table :data="record_list" style="width: 100%" row-key="id" @selection-change="handleSelectionChange">

    <!-- 多选框 -->
    <el-table-column type="selection" width="55"/>

    <!--选择框-->
    <el-table-column label="大类名称" prop="big_name" v-if="table_head_optional.big_name"/>
    <el-table-column label="小类名称" prop="small_name" v-if="table_head_optional.small_name"/>
    <el-table-column label="编号" prop="no" v-if="table_head_optional.no"/>
    <el-table-column label="型号" prop="small__model" v-if="table_head_optional.small__model"/>
    <el-table-column label="日期" prop="actual_date_str" v-if="table_head_optional.actual_date_str"/>
    <el-table-column label="处理方" prop="handle_name" v-if="table_head_optional.handle_name"/>
    <el-table-column label="出入库" prop="trend" v-if="table_head_optional.trend">
      <template #default="scope: {row:RecordInfo}">
        <span>{{ scope.row.trend === true ? '出库 ' : '入库' }}</span>
      </template>
    </el-table-column>
    <el-table-column label="单位" prop="units" v-if="table_head_optional.units"/>
    <el-table-column label="数量" prop="change" v-if="table_head_optional.change"/>
    <el-table-column label="加权单价" prop="unit_price" v-if="table_head_optional.unit_price"/>
    <el-table-column label="实际单价" prop="real_unit_price" v-if="table_head_optional.real_unit_price"/>
    <el-table-column label="总价" prop="total" v-if="table_head_optional.total"/>
    <el-table-column label="库存" prop="last_number" v-if="table_head_optional.last_number"/>
    <el-table-column label="修改人" prop="operator" v-if="table_head_optional.operator"/>
    <el-table-column label="修改时间" prop="operate_date_str" v-if="table_head_optional.operate_date_str"/>
    <el-table-column label="备注" prop="remarks" v-if="table_head_optional.remarks"/>
    <el-table-column align="right" width="140px">
      <template #header>
      </template>

      <template #default="scope">
        <!--			<el-button size="small" @click="handleRecordEdit(scope.$index, scope.row)">修改</el-button>-->
        <el-button size="small" type="danger" @click="handleRecordDelete(scope.row)">删除</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!-- 分页 -->
  <el-pagination
      v-model:current-page="record_currentPage"
      v-model:page-size="record_pageSize"
      :page-sizes="[100, 200, 500]"
      :small="false"
      :disabled="record_disabled"
      :background="record_background"
      layout="total, sizes, prev, pager, next, jumper"
      :total=" record_total "
  />

  <el-dialog
      v-model="record_head_show_visible"
      title="表头选项"
      :close-on-click-modal='false'
      :close-on-press-escape='false'
      :show-close='false'
  >
    <el-checkbox v-model="table_head_optional.big_name" label="大类名称"/>
    <el-checkbox v-model="table_head_optional.small_name" label="小类名称"/>
    <el-checkbox v-model="table_head_optional.no" label="编号"/>
    <el-checkbox v-model="table_head_optional.small__model" label="型号"/>
    <el-checkbox v-model="table_head_optional.actual_date_str" label="日期"/>
    <el-checkbox v-model="table_head_optional.handle_name" label="处理方"/>
    <el-checkbox v-model="table_head_optional.trend" label="出入库"/>
    <el-checkbox v-model="table_head_optional.units" label="单位"/>
    <el-checkbox v-model="table_head_optional.change" label="数量"/>
    <el-checkbox v-model="table_head_optional.unit_price" label="加权单价"/>
    <el-checkbox v-model="table_head_optional.real_unit_price" label="实际单价"/>
    <el-checkbox v-model="table_head_optional.total" label="总价"/>
    <el-checkbox v-model="table_head_optional.last_number" label="库存"/>
    <el-checkbox v-model="table_head_optional.operator" label="修改人"/>
    <el-checkbox v-model="table_head_optional.operate_date_str" label="修改时间"/>
    <el-checkbox v-model="table_head_optional.remarks" label="备注"/>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="record_table_head_show()">确定</el-button>
      </span>
    </template>
  </el-dialog>

  <!-- TODO 添加框 -->
  <el-dialog
      v-model="add_or_update_record_visible"
      :title="add_or_update_record_signal"
      :close-on-click-modal='false'
      :close-on-press-escape='false'
      :show-close='false'
  >

    <el-form :model="add_or_update_record_variable" :rules="add_or_update_record_rules" ref="add_or_update_record_ref"
             :label-position=" 'right' " label-width="90px">

      <el-form-item prop="small" label="小类名称">
        <el-input v-model="add_or_update_record_variable.small" autocomplete="off" disabled/>
      </el-form-item>

      <el-form-item label="小类补全">
        <FuzzySearchSmallVer2 @DataUse="small_auto_complete_in_record_dialog($event as any)" ref="small_clear_dialog"
                              :disable="isdisabled"
                              :clear="true"></FuzzySearchSmallVer2>
      </el-form-item>
      <!--actual_date-->
      <el-form-item label="出入库时间">
        <el-date-picker
            v-model="add_or_update_record_variable.actual_date"
            type="datetime"
            placeholder="选择日期时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <!-- handle -->
      <el-form-item prop="handle" label="处理方名称">
        <el-input v-model="add_or_update_record_variable.handle" autocomplete="off" disabled/>
      </el-form-item>

      <el-form-item label="处理方补全">
        <FuzzySearchHandleVer2 @DataUse="handle_auto_complete_in_record_dialog($event as any)" ref="handle_clear_dialog"
                               :disable="false"
                               :clear="true"></FuzzySearchHandleVer2>

      </el-form-item>

      <!--change-->
      <el-form-item prop="change" label="数量">
        <el-input v-model="add_or_update_record_variable.change" autocomplete="off"/>
      </el-form-item>
      <!-- unit_price -->
      <el-form-item prop="unit_price" label="实际单价">
        <el-input v-model.number="add_or_update_record_variable.real_unit_price" autocomplete="off"/>
      </el-form-item>
      <!-- trend -->
      <el-form-item prop="trend" label="出入库">
        <el-radio-group v-model="add_or_update_record_variable.trend">
          <el-radio-button :label="true">出库</el-radio-button>
          <el-radio-button :label="false">入库</el-radio-button>
        </el-radio-group>
      </el-form-item>
      <!-- remarks -->
      <el-form-item prop="remarks" label="备注">
        <el-input v-model="add_or_update_record_variable.remarks" autocomplete="off"/>
      </el-form-item>

    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="add_or_update_record()">确定</el-button>
        <el-button @click="cancel_add_or_update_record()">取消</el-button>
      </span>
    </template>
  </el-dialog>
</template>


<script lang="ts" setup>
import {reactive, ref, watch} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {
  RecordInfo, RecordTableCRUDResponseData,
  SmallInfo
} from "@/api/first/PartsManagement/type.ts";
import {
  reqRecordList,
} from "@/api/first/PartsManagement";
import {ElMessage, ElMessageBox} from "element-plus";
import type {SmallAutoCompletion} from "@/components/first/FuzzySearchSmallVer2.vue";
import type {HandleAutoCompletion} from "@/components/first/FuzzySearchHandleVer2.vue";
import {useStore} from "@/pinia"
import {InboundListData} from "@/api/first/ExportFile/type.ts";
import {reqInboundList} from "@/api/first/ExportFile";
import FuzzySearchSmallVer2 from "@/components/first/FuzzySearchSmallVer2.vue";
import FuzzySearchHandleVer2 from "@/components/first/FuzzySearchHandleVer2.vue";

const store = useStore()


// ========================================
// 生成入库单
// ========================================
const multipleSelection = ref<RecordInfo[]>([])
const handleSelectionChange = (val: RecordInfo[]) => {
  multipleSelection.value = val
}
const return_inbound_list = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请至少选择一条记录')
    return
  }

  let result: InboundListData[] = []

  for (let i of multipleSelection.value) {
    let inbound_list_line: InboundListData = {
      small_name: '',
      model: '',
      units: '',
      change: '0',
      unit_price: '0',
      total: '0',
    }
    inbound_list_line.small_name = i.small_name
    inbound_list_line.model = i.small__model
    inbound_list_line.units = i.units
    inbound_list_line.change = i.change
    inbound_list_line.unit_price = i.unit_price
    inbound_list_line.total = i.total
    result.push(inbound_list_line)
  }

  await reqInboundList({
    data: result,
    handle_name: multipleSelection.value[0].handle_name,
    date: multipleSelection.value[0].actual_date_str.split(' ')[0],
  })
}


// 当前页面所属大类信息和小类信息存储
// 样例： id：2 info：大类2，大类2小类1，2023-07-02
const record_page_search_info = reactive<{
  big_name_and_small_name: string
  handle_name: string
}>({
  big_name_and_small_name: '无',
  handle_name: '无'
})

// todo 明细表添加或修改操作

const add_or_update_record_visible = ref(false) // 决定添加和修改框是否显示
const add_or_update_record_signal = ref('') // 决定添加和修改框的标题显示

// 选择模糊搜索结果之后，清除之前的模糊搜索结果
const handle_clear_dialog = ref()
const small_clear_dialog = ref()
const small_auto_complete_in_record_dialog = (cmy: SmallAutoCompletion) => {
  add_or_update_record_variable.small = cmy.big_name + '-' + cmy.small_name
  add_or_update_record_variable.small_id = cmy.small_id as number
  handle_clear_dialog.value.clear_input
}
const handle_auto_complete_in_record_dialog = (cmy: HandleAutoCompletion) => {
  add_or_update_record_variable.handle = cmy.handle_name
  add_or_update_record_variable.handle_id = cmy.handle_id as number
  small_clear_dialog.value.clear_input
}

// 添加和修改框所需要的变量，该框内模糊查询所需要的变量
const add_or_update_record_variable = reactive<{
  actual_date: string
  change: string | number
  real_unit_price: number | undefined
  trend: boolean | undefined
  remarks: string

  small_id: number | undefined
  handle_id: number | undefined

  small: string
  handle: string

  record_id: number | undefined

}>({
  actual_date: '',
  change: '',
  real_unit_price: undefined,
  trend: undefined,
  remarks: '',

  small_id: undefined,
  handle_id: undefined,

  small: '',
  handle: '',

  record_id: undefined,
})
// 将添加和修改框内的数据清空，在这个框备关闭之前
const recover_record = () => {
  add_or_update_record_variable.actual_date = ''
  add_or_update_record_variable.change = ''
  add_or_update_record_variable.real_unit_price = undefined
  add_or_update_record_variable.trend = undefined
  add_or_update_record_variable.remarks = ''
  add_or_update_record_variable.small_id = undefined
  add_or_update_record_variable.handle_id = undefined
  add_or_update_record_variable.small = ''
  add_or_update_record_variable.handle = ''
}
// 关闭添加或修改框
const cancel_add_or_update_record = () => {
  add_or_update_record_visible.value = false
  // 清理输入框中的所有数据
  recover_record()
  isdisabled.value = false
}
// 对明细表添加和修改框中需要输入数字的地方进行校验
const check_float = (value: any, callback: any) => {
  let reg = /^[+-]?(0|([1-9]\d*))(\.\d+)?$/g;
  if (value === '') {
    callback(new Error('请输入内容'));
  } else if (!reg.test(value)) {
    callback(new Error('请输入数字'));
  } else {
    callback();
  }
}
// 对明细表添加和修改框中的数据进行校验
const add_or_update_record_rules = reactive<FormRules>({
  small: [{
    required: true,
    message: "请选择小类名称"
  }],
  handle: [{
    required: true,
    message: "请选择处理方"
  }],
  change: [{
    message: '请输入数字',
    required: true,
    validator: check_float
  }],
  unit_price: [{
    type: 'float',
    message: '请输入数字',
    validator: check_float
  }],
  remarks: [{
    type: 'string',
    message: '请输入字符串',
  }],
  trend: [{
    required: true
  }]
})


// todo 打开明细表修改框
const isdisabled = ref(false)  // 值为真时将禁止在明细表添加或修改框中修改小类

// 在明细表添加或修改框中 点击确认，请求后端
const add_or_update_record = async () => {
  await add_or_update_record_ref.value?.validate()  // 表单验证
  // 如果不写日期那默认就是现在，后端会处理这个now
  let actual_date_temp: string
  if (add_or_update_record_variable.actual_date === '') {
    actual_date_temp = 'now'
  } else {
    actual_date_temp = add_or_update_record_variable.actual_date
  }
  // 为了防止选了出库但是没有输入负号，这里自动校正
  let change_temp: number = 0


  if (typeof add_or_update_record_variable.change === "number") {
    if (!add_or_update_record_variable.trend && add_or_update_record_variable.change < 0) {
      change_temp = -add_or_update_record_variable.change
    } else if (add_or_update_record_variable.trend && add_or_update_record_variable.change > 0) {
      change_temp = -add_or_update_record_variable.change
    } else {
      change_temp = add_or_update_record_variable.change as number
    }
  }

  if (add_or_update_record_signal.value === '添加记录') {
    const result: RecordTableCRUDResponseData = await reqRecordList({
      mode: "create",
      create: {
        list: [{
          actual_date: actual_date_temp,
          handle: add_or_update_record_variable.handle_id as number,
          change: change_temp as number,
          unit_price: add_or_update_record_variable.real_unit_price as number,
          trend: add_or_update_record_variable.trend as boolean,
          remarks: add_or_update_record_variable.remarks,
          small: add_or_update_record_variable.small_id as number,
          index: 1,
          operator: store.username,
        }]
      },
    })
    if (result.create ?.[0].error) {
      ElMessage.warning(result.create ?.[0].error)
    } else {
      // 刷新当前页面
      return_record_list()
      ElMessage.success('创建记录成功')
    }
  } else {
    // 修改的情况
    await reqRecordList({
      mode: "update",
      update: {
        record_id: add_or_update_record_variable.record_id as number,
        operator: store.username,
        actual_date: actual_date_temp,
        change: change_temp as number,
        unit_price: add_or_update_record_variable.real_unit_price as number,
        trend: add_or_update_record_variable.trend as boolean,
        remarks: add_or_update_record_variable.remarks,
        handle_id: add_or_update_record_variable.handle_id as number,
      },
    })
    // 这个东西只返回成功或失败
    return_record_list()
    ElMessage.success('修改成功')
  }
  add_or_update_record_visible.value = false
  recover_record()
  isdisabled.value = false
}

// todo 明细表表头处理
const table_head_select = () => {
  record_head_show_visible.value = true
}
// 决定record表表头哪些要显示哪些要隐藏
const record_head_show_visible = ref<boolean>()
const record_table_head_show = () => {
  record_head_show_visible.value = false
}

const table_head_optional = reactive({
  big_name: true,
  small_name: true,
  no: true,
  actual_date_str: true,
  handle_name: true,
  trend: false,
  units: true,
  change: true,
  unit_price: true,
  real_unit_price: false,
  total: true,
  last_number: true,
  operator: false,
  operate_date_str: false,
  remarks: false,
  small__model: true,
})

// record 明细表删除
const handleRecordDelete = async (row: SmallInfo) => {
  await ElMessageBox.confirm(
      `您确认要删除该条记录吗`, '注意',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'info',
      }
  )
  const result: RecordTableCRUDResponseData = await reqRecordList({
    mode: "delete",
    delete: {
      record_id: row.id,
      operator: store.username,
    }
  })
  // 在队列中将其删除
  if (result.error) {
    ElMessage.warning(result.error.message)
  } else {
    return_record_list()
    ElMessage.success('删除成功')
  }
}

// todo 明细表请求数据
// 模糊搜索需要返回的数据
const record_fuzzy_search = reactive<{
  small_id: number | string  // 小类的id或者处理方的id
  handle_id: number | string
  date_range: string  // 时间范围
  trend: '出库' | '入库' | '全部'   // 入库还是出库还是都要
  scale: number // 显示价格和数量时允许的小数位数
}>({
  small_id: '',
  handle_id: '',
  date_range: '',
  trend: '出库',
  scale: 2,
})

// 返回数据模糊搜索
const small_clear = ref()
const handle_clear = ref()

// 小类搜索组件中清除当前所选小类后，同步清除
const small_auto_complete_in_record_clear = () => {
  record_page_search_info.big_name_and_small_name = '无'
  record_fuzzy_search.small_id = ''
}

const small_auto_complete_in_record = (cmy: SmallAutoCompletion) => {
  record_fuzzy_search.small_id = cmy.small_id as number
  record_page_search_info.big_name_and_small_name = cmy.big_name + '-' + cmy.small_name
}

const handle_auto_complete_in_record_clear = () => {
  record_page_search_info.handle_name = '无'
  record_fuzzy_search.handle_id = ''
}

// 处理方搜索组件中选定处理方
const handle_auto_complete_in_record = (cmy: HandleAutoCompletion) => {
  record_fuzzy_search.handle_id = cmy.handle_id as number
  record_page_search_info.handle_name = cmy.handle_name
}

// 返回小类数据
const return_record_list = () => {
  if (record_fuzzy_search.date_range === '') {
    ElMessage.warning('必须输入日期范围')
    return
  }
  let date_start
  let date_stop
  if (record_fuzzy_search.date_range === '') {
    date_start = ''
    date_stop = ''
  } else {
    date_start = record_fuzzy_search.date_range[0]
    date_stop = record_fuzzy_search.date_range[1]
  }
  reqRecordList({
    mode: 'read',
    read: {
      small_id: record_fuzzy_search.small_id,
      handle_id: record_fuzzy_search.handle_id,
      start_date: date_start,
      stop_date: date_stop,
      in_out: record_fuzzy_search.trend,
      start: (record_currentPage.value - 1) * record_pageSize.value,
      stop: record_currentPage.value * record_pageSize.value,
    }
  }).then((res: RecordTableCRUDResponseData) => {
    if(record_fuzzy_search.scale !== 4){
      for(let i of res.read?.record_list as RecordInfo[]){
        i.total = i.total.slice(0,record_fuzzy_search.scale-4)
        i.real_unit_price = i.real_unit_price.slice(0,record_fuzzy_search.scale-4)
        i.unit_price = i.unit_price.slice(0,record_fuzzy_search.scale-4)
        i.change = i.change.slice(0,record_fuzzy_search.scale-4)
        i.last_number = i.last_number.slice(0,record_fuzzy_search.scale-4)
      }
    }
    record_list.value = res.read?.record_list as RecordInfo[]

    record_total.value = res.read?.total as number
    ElMessage.success(res.success?.message)
  })
}

// 分页
const record_background = ref<boolean>(true)  // 是否带背景方框
const record_disabled = ref<boolean>(false)  // 是否可用
const record_currentPage = ref<number>(1)  // 当前所在页数
const record_pageSize = ref<number>(100)  // 一页有几条记录
const record_total = ref<number>(0) // 总条数
// 在分页数据变动后重新返回数据
watch([record_currentPage, record_pageSize], () => {
  // 直接模拟按确定键完事
  return_record_list()
})

const add_or_update_record_ref = ref<FormInstance>() // 增删改查表单的ref
const record_list = ref<RecordInfo[]>([]) // 明细表数据变量
const record_query_form = ref<FormInstance>()// 设定返回明细表数据的ref
</script>

<style scoped>

</style>